import json
import os
from pathlib import Path
from typing import Any, Dict, List, Optional
from .logger import logger

class Config:
    _instance = None
    _initialized = False

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Config, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if Config._initialized:
            return
            
        Config._initialized = True
        
        # 配置文件路径
        self.config_dir = Path("config")
        self.config_file = self.config_dir / "settings.json"
        
        # 确保配置目录存在
        self.config_dir.mkdir(exist_ok=True)
        
        # 加载配置
        self.settings = self._load_config()

    def _load_config(self) -> Dict:
        """加载配置文件"""
        try:
            if self.config_file.exists():
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            return self._get_default_config()
            
        except Exception as e:
            logger.error(f"加载配置文件失败: {str(e)}")
            return self._get_default_config()

    def _get_default_config(self) -> Dict:
        """获取默认配置"""
        return {
            'ui': {
                'theme': 'light',
                'language': '简体中文',
                'show_notifications': True,
                'minimize_to_tray': True
            },
            'video': {
                'directory': 'videos',
                'format': 'mp4',
                'fps': 30,
                'record_audio': True,
                'allowed_formats': [
                    '.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv'
                ]
            },
            'auto_publish': {
                'enabled': False,
                'interval': 30,
                'max_retries': 3,
                'retry_delay': 5
            },
            'platforms': {
                'douyin': {
                    'enabled': False,
                    'credentials': {}
                },
                'bilibili': {
                    'enabled': False,
                    'credentials': {}
                },
                'xiaohongshu': {
                    'enabled': False,
                    'credentials': {}
                }
            },
            'system': {
                'debug': False,
                'temp_dir': 'temp',
                'log_level': 'INFO'
            }
        }

    def save_config(self) -> bool:
        """保存配置到文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.settings, f, indent=4, ensure_ascii=False)
            logger.info("配置文件保存成功")
            return True
            
        except Exception as e:
            logger.error(f"保存配置文件失败: {str(e)}")
            return False

    def get(self, key: str, default: Any = None) -> Any:
        """获取配置项"""
        try:
            # 支持使用点号访问嵌套配置
            value = self.settings
            for k in key.split('.'):
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default

    def set(self, key: str, value: Any) -> bool:
        """设置配置项"""
        try:
            # 支持使用点号设置嵌套配置
            keys = key.split('.')
            target = self.settings
            
            # 遍历到最后一个键之前
            for k in keys[:-1]:
                if k not in target:
                    target[k] = {}
                target = target[k]
                
            # 设置最后一个键的值
            target[keys[-1]] = value
            
            # 保存配置
            return self.save_config()
            
        except Exception as e:
            logger.error(f"设置配置项失败: {str(e)}")
            return False

    def reset(self) -> bool:
        """重置为默认配置"""
        try:
            self.settings = self._get_default_config()
            return self.save_config()
            
        except Exception as e:
            logger.error(f"重置配置失败: {str(e)}")
            return False

    def merge(self, new_settings: Dict) -> bool:
        """合并新的配置"""
        try:
            def deep_update(target: Dict, source: Dict):
                for key, value in source.items():
                    if key in target and isinstance(target[key], dict) and isinstance(value, dict):
                        deep_update(target[key], value)
                    else:
                        target[key] = value
            
            deep_update(self.settings, new_settings)
            return self.save_config()
            
        except Exception as e:
            logger.error(f"合并配置失败: {str(e)}")
            return False

# 创建全局配置实例
config = Config()

# 导出便捷函数
def get(key: str, default: Any = None) -> Any:
    return config.get(key, default)

def set(key: str, value: Any) -> bool:
    return config.set(key, value)

def reset() -> bool:
    return config.reset()

def merge(new_settings: Dict) -> bool:
    return config.merge(new_settings)

def save() -> bool:
    return config.save_config()
